package me.boot.db.mybatis.interceptor.foreign;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import lombok.Getter;
import me.boot.db.mybatis.handler.CommaToListTypeHandler;
import me.boot.db.mybatis.template.entity.Entity;
import me.boot.db.mybatis.utils.MpUtils;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @author: Sylar
 * @date: 2021年10月14日 8:06 下午
 */
@SuppressWarnings("rawtypes")
public class RegisterDetail {
    @Getter
    Class<? extends Entity> pkClass;
    @Getter
    Class<? extends Entity> fkClass;
    String fkProperty;
    String fkColumn;

    public RegisterDetail(Class<? extends Entity> pkClass,
                          Class<? extends Entity> fkClass,
                          String fkProperty) {
        this.pkClass = pkClass;
        this.fkClass = fkClass;
        this.fkProperty = fkProperty;
    }

    public TableInfo getPkTable() {
        return TableInfoHelper.getTableInfo(pkClass);
    }


    public TableInfo getFkTable() {
        return TableInfoHelper.getTableInfo(fkClass);
    }

    public String getFkColumn() {
        if (fkColumn == null) {
            fkColumn = Objects.requireNonNull(getFkTable().getFieldList()
                    .stream()
                    .filter(f -> f.getProperty().equals(fkProperty))
                    .findFirst()
                    .orElse(null))
                    .getColumn();
        }
        return fkColumn;
    }


    /**
     * 查找存在外键值的记录
     *
     * @param sqlSessionTemplate sqlSessionTemplate
     * @param fkValue            外键值
     * @return 存在引用的记录列表
     */
    public List<Entity> findByFK(SqlSessionTemplate sqlSessionTemplate, Object fkValue) {
        TableInfo tableInfo = getFkTable();
        BaseMapper<Entity> mapper = MpUtils.getMapper(sqlSessionTemplate, tableInfo);

        String fkColumn = getFkColumn();
        QueryWrapper<Entity> wrapper = new QueryWrapper<>();
        wrapper.select(tableInfo.getKeyColumn());

        if (CommaToListTypeHandler.isSplitterField(fkClass, fkColumn)) {
            //分隔符存储的id列表
            String applySql = String.format("find_in_set({0}, %s) > 0", fkColumn);
            wrapper.apply(applySql, fkValue);
        } else {
            wrapper.eq(fkColumn, fkValue);
        }

        return mapper.selectList(wrapper);
    }

}
